import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
import pinia from "@/stores";
import useUserStore from "@/stores/modules/userStore";



const request = axios.create({
  baseURL: "http://127.0.0.1:3000/api",
  timeout: 10000,
});
//请求拦截器
request.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearea ${token}`;
    }
    return config;
  },
  (error) => {
    console.log(2);
    ElMessage.error("请求超时");
    return new Promise.reject(new Error(error));
  }
);
//响应拦截器
request.interceptors.response.use(
  (res) => {
    if (res.data.code == 200) {
      return res.data;
    } else {
      console.log(11);
      ElMessage.error(res.data.message);
      return new Promise.reject(new Error(res.data.message));
    }
  },
  (error) => {
    console.log(error);
    //401的状态稍后完成
    if (error.response?.status == 401) {
        let userStore = useUserStore(pinia);
      userStore.logout();
      router.push("/login");
      ElMessage.error("token过期，请重新登录");
    } else {
      ElMessage.error(error.response.data?.message || '服务器异常');
    }
  }
);

export default request;
